# -*- coding: utf-8 -*-
from django.template import RequestContext
from django.template import Context
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator,PageNotAnInteger, EmptyPage
from django.contrib.auth.models import User

from cprt.admin.models import Dept,get_my_depts,get_my_branchs2
from cprt.schedule.forms import ComposeReviewForm
from cprt.accounts.models import UserDetail
from cprt.schedule.models import ScheduleType, Schedule
from cprt import createExtInfo,get_200_response,get_date_range

@login_required
def index(request):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    schedule_list = Schedule.objects.filter(created_by=request.user.id,status__gte=1,start_date__gte=dt1.strftime("%Y-%m-%d"),end_date__lte=dt2.strftime("%Y-%m-%d"))
    paginator = Paginator(schedule_list,20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("review/list.html",c)

@login_required
def list_unfinished(request):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    schedule_list = Schedule.objects.filter(created_by=request.user.id,status__gte=2,start_date__gte=dt1.strftime("%Y-%m-%d"),end_date__lte=dt2.strftime("%Y-%m-%d"))
    paginator = Paginator(schedule_list,20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("review/unfinished.html",c)

@login_required
def my_dept(request,id):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))    
    try:
        dept = Dept.objects.get(pk=id)
    except Dept.DoesNotExits:
        raise Http404

    if dept == None or dept.principal_auth_user_id != request.user.id:
        raise Http404
    
    query_set = Schedule.objects.raw("select S.* from SCHEDULE S inner join USER_DETAIL U on S.created_by_id = U.user_id where S.start_date >= '%s' and S.end_date <= '%s' and U.dept_id = %d and S.status = 3" % (dt1.strftime("%Y-%m-%d"),dt2.strftime("%Y-%m-%d"),dept.id))
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))    
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c = RequestContext(request,{"list":data_list,"who":dept.name})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("review/dept.html",c)

@login_required
def list_by_user(request,id):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2')) 
    try:
        user = User.objects.get(pk=id)
    except User.DoesNotExits:
        raise Http404

    schedule_list = Schedule.objects.filter(created_by=user,status=3,start_date__gte=dt1.strftime("%Y-%m-%d"),end_date__lte=dt2.strftime("%Y-%m-%d")) #raw("select S.* from SCHEDULE S inner join USER_DETAIL U on S.created_by = U.user_id where U.dept_id = %d and S.status = 3" % dept.id)
    paginator = Paginator(schedule_list,20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    c = RequestContext(request,{"list":data_list,"who":user.last_name})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("review/dept.html",c)

@login_required    
def branch(request,id):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    try:
        dept = Dept.objects.get(pk=id)
    except Dept.DoesNotExist:
        raise Http404
    branchs = get_my_branchs2(request.user)
    if dept == None or dept not in branchs:
        raise Http404
    query_set = Schedule.objects.raw("select S.* from SCHEDULE S inner join USER_DETAIL U on S.created_by_id = U.user_id where S.start_date>= '%s' and S.end_date <= '%s' and U.dept_id = %s and S.status = 3" % (dt1.strftime("%Y-%m-%d"),dt2.strftime("%Y-%m-%d"),id))
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))    
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    
    c = RequestContext(request,{"list":data_list,"who":dept.name})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("review/dept.html",c)

@login_required
def compose(request, id):
    try:
        schedule = Schedule.objects.get(pk=id)
    except Schedule.DoesNotExist:
        raise Http404

    if request.method == 'POST':
        form = ComposeReviewForm(request.POST,instance=schedule)
        if form.is_valid():
            is_commit = 'commit' in request.POST
            if is_commit:
                form.commit_review()
            else:
                form.save()
            return get_200_response("review_list_page","closeCurrent","/review/")
    else:
        form = ComposeReviewForm(instance=schedule)
        c = RequestContext(request,{"form":form})
        c.update(csrf(request))
        createExtInfo(request,c)
        return render_to_response("review/compose.html",c)

@login_required
def commit(request, id):
    try:
        schedule = Schedule.objects.get(pk=id)
    except Schedule.DoesNotExist:
        raise Http404

    if request.method == 'POST':
        form = ComposeReviewForm(request.POST,instance=schedule)
        if form.is_valid():
            form.commit_review()
            return get_200_response("review_list_page","closeCurrent","/review/")
    else:
        form = ComposeReviewForm(instance=schedule)
        c = RequestContext(request,{"form":form})
        c.update(csrf(request))
        createExtInfo(request,c)
        return render_to_response("review/compose.html",c)
